package com.ruoyi.infoprojectplan.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.baselibrary.infobasecategory.domain.InfoBaseCategory;
import com.ruoyi.baselibrary.infobasecategory.service.IInfoBaseCategoryService;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.infoprojecttarget.domain.InfoProjectTarget;
import com.ruoyi.project.infoprojecttarget.mapper.InfoProjectTargetMapper;
import com.ruoyi.project.infoprojecttarget.service.IInfoProjectTargetService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Arg;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.infoprojectplan.domain.InfoProjectPlan;
import com.ruoyi.infoprojectplan.service.IInfoProjectPlanService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 项目汇总Controller
 *
 * @author ruoyi
 * @date 2023-08-01
 */
@RestController
@RequestMapping("/infoprojectplan/infoprojectplan")
public class InfoProjectPlanController extends BaseController {
    @Autowired
    private IInfoProjectPlanService infoProjectPlanService;
    @Autowired
    private IInfoBaseCategoryService infoBaseCategoryService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysConfigService iSysConfigService;
    @Autowired
    private InfoProjectTargetMapper infoProjectTargetMapper;
    @Autowired
    private ISysDeptService iSysDeptService;


    /**
     * 查询项目汇总列表
     */
    @PreAuthorize("@ss.hasPermi('infoprojectplan:infoprojectplan:list')")
    @GetMapping("/list")
    public TableDataInfo list(InfoProjectPlan infoProjectPlan) {
        List<InfoProjectPlan> list1 = infoProjectPlanService.selectInfoProjectPlanList(infoProjectPlan);
        BigDecimal reduce = list1.stream().map(InfoProjectPlan::getFundSum).reduce(BigDecimal.ZERO, BigDecimal::add);
        Long userId = SecurityUtils.getUserId();
        List<String> collect = sysUserService.selectUserById(userId).getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        //财政局和乡村振兴局查询所有
        //主管单位查询子单位和自己的
        if (collect.contains("common")) {
            infoProjectPlan.setSponsorId(SecurityUtils.getDeptId());
            infoProjectPlan.setImplementId(SecurityUtils.getDeptId());
        }
        if (collect.contains("dept")) {
            infoProjectPlan.setSponsorId(SecurityUtils.getDeptId());
        }
        startPage();
        //查询当前登录单位自己的
        List<InfoProjectPlan> list = infoProjectPlanService.selectInfoProjectPlanList(infoProjectPlan);

        TableDataInfo dataTable = getDataTable(list);
        if (StringUtils.isNotNull(reduce)){
            dataTable.setTotalSum(reduce.toString());
        }
        return dataTable;
    }

    /**
     * 统计
     *
     * @return
     */
    @GetMapping("/statistics")
    public AjaxResult statistics() {
        List<String> collect = sysUserService.selectUserById(SecurityUtils.getUserId()).getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        InfoProjectPlan infoProjectPlan = new InfoProjectPlan();
        if (collect.contains("common")) {
            infoProjectPlan.setImplementId(SecurityUtils.getDeptId());
            infoProjectPlan.setSponsorId(SecurityUtils.getDeptId());
        }
        if (collect.contains("dept")) {
            infoProjectPlan.setImplementId(SecurityUtils.getDeptId());
        }
        List<InfoProjectPlan> list = infoProjectPlanService.selectInfoProjectPlanList(infoProjectPlan);
        int size = list.size();
        BigDecimal reduce = list.stream().map(InfoProjectPlan::getFundSum).reduce(BigDecimal.ZERO, BigDecimal::add);
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("projectSum", String.valueOf(size));
        stringStringHashMap.put("totalFund", String.valueOf(reduce));
        return AjaxResult.success(stringStringHashMap);
    }

    /**
     * 导出项目汇总列表
     */
    @PreAuthorize("@ss.hasPermi('infoprojectplan:infoprojectplan:export')")
    @Log(title = "项目汇总", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InfoProjectPlan infoProjectPlan) {
        List<InfoProjectPlan> list = infoProjectPlanService.selectInfoProjectPlanList(infoProjectPlan);
        ExcelUtil<InfoProjectPlan> util = new ExcelUtil<InfoProjectPlan>(InfoProjectPlan.class);
        util.exportExcel(response, list, "项目汇总数据");
    }

    /**
     * 获取项目汇总详细信息
     */
    @PreAuthorize("@ss.hasPermi('infoprojectplan:infoprojectplan:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(infoProjectPlanService.selectInfoProjectPlanById(id));
    }

    /**
     * 新增项目汇总
     */
    @PreAuthorize("@ss.hasPermi('infoprojectplan:infoprojectplan:add')")
    @Log(title = "项目汇总", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InfoProjectPlan infoProjectPlan) {
        return toAjax(infoProjectPlanService.insertInfoProjectPlan(infoProjectPlan));
    }

    /**
     * 修改项目汇总
     */
    @PreAuthorize("@ss.hasPermi('infoprojectplan:infoprojectplan:edit')")
    @Log(title = "项目汇总", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InfoProjectPlan infoProjectPlan) {
        return toAjax(infoProjectPlanService.updateInfoProjectPlan(infoProjectPlan));
    }

    /**
     * 删除项目汇总
     */
    @PreAuthorize("@ss.hasPermi('infoprojectplan:infoprojectplan:remove')")
    @Log(title = "项目汇总", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(infoProjectPlanService.deleteInfoProjectPlanByIds(ids));
    }


    @GetMapping("/downloadFundDocument")
    public AjaxResult downloadFundDocument() {
        String fileAddress = iSysConfigService.selectConfigByKey("FUND_DOCUMENTS");
        File file = new File(fileAddress);
        if (file.exists()) {
            return AjaxResult.success(fileAddress);
        } else {
            return AjaxResult.error("文件不存在！");
        }
    }

    /**
     * 导入
     *
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/excelImport")
    public AjaxResult excelImport(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = workbook.getSheetAt(0);
            int rows = sheet.getPhysicalNumberOfRows();
            //前六行为表头
            Long categoryId = null;
            for (int i = 6; i < rows; i++) {
                XSSFRow row = sheet.getRow(i);
                //判断是否是空行
                if (!(row.getPhysicalNumberOfCells() <= 0)) {
                    XSSFCell cell = row.getCell(0);
                    if (cell != null) {


                        if (cell.getCellType() == CellType.NUMERIC) {
                            // 如果单元格是数字类型，则将其转换为字符串类型
                            cell.setCellType(CellType.STRING);
                        }
                        //项目计划表编号
                        String id = cell.getStringCellValue();
                        //获取项目名称
                        //获取项目属性
                        //获取项目总金额
                        XSSFCell cell1 = row.getCell(1);
                        String category = cell1.getStringCellValue();
                        //判断是否到项目具体信息

                        if (category.contains("方面") && "".equals(row.getCell(2).getStringCellValue())) {
                            InfoBaseCategory infoBaseCategory = new InfoBaseCategory();
                            infoBaseCategory.setCategory("project_plan");
                            infoBaseCategory.setCategoryName(category);
                            InfoBaseCategory infoBaseCategory1 = infoBaseCategoryService.selectInfoBaseCategory(infoBaseCategory);
                            if (!StringUtils.isNotNull(infoBaseCategory1)) {
                                infoBaseCategoryService.insertInfoBaseCategory(infoBaseCategory);
                            }
                            InfoBaseCategory infoBaseCategory2 = infoBaseCategoryService.selectInfoBaseCategory(infoBaseCategory);
                            categoryId = infoBaseCategory2.getId();
                        }
                        if (isNumeric(id)) {
                            InfoProjectPlan infoProjectPlan = new InfoProjectPlan();
                            infoProjectPlan.setCategoryId(categoryId);
                            infoProjectPlan.setProjectName(row.getCell(1).getStringCellValue());
                            infoProjectPlan.setProjectAttribute(row.getCell(2).getStringCellValue());
                            infoProjectPlan.setProjectStage(row.getCell(3).getStringCellValue());
                            infoProjectPlan.setProjectLocation(StringUtils.isNotEmpty(row.getCell(4).getStringCellValue()) ? row.getCell(4).getStringCellValue() : null);
                            infoProjectPlan.setProjectContent(row.getCell(5).getStringCellValue());
                            infoProjectPlan.setFundSum(new BigDecimal(row.getCell(6).getNumericCellValue()));
                            if (row.getCell(7).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                cell.setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setCentreFund(new BigDecimal(StringUtils.isNotEmpty(row.getCell(7).getStringCellValue()) ? row.getCell(7).getStringCellValue() : "0.00"));
                            if (row.getCell(8).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                row.getCell(8).setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setProvincialLevelFund(new BigDecimal(StringUtils.isNotEmpty(row.getCell(8).getStringCellValue()) ? row.getCell(8).getStringCellValue() : "0.00"));
                            if (row.getCell(9).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                row.getCell(9).setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setMunicipalLevelFund(new BigDecimal(StringUtils.isNotEmpty(row.getCell(9).getStringCellValue()) ? row.getCell(9).getStringCellValue() : "0.00"));
                            if (row.getCell(10).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                row.getCell(10).setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setCountyLevelFund(new BigDecimal(StringUtils.isNotEmpty(row.getCell(10).getStringCellValue()) ? row.getCell(10).getStringCellValue() : "0.00"));
                            //资金来源暂时不加
                            if (row.getCell(12).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                row.getCell(12).setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setProjectBenefits(StringUtils.isNotEmpty(row.getCell(12).getStringCellValue()) ? row.getCell(12).getStringCellValue() : null);
                            if (row.getCell(13).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                row.getCell(13).setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setJointMechanism(StringUtils.isNotEmpty(row.getCell(13).getStringCellValue()) ? row.getCell(13).getStringCellValue() : null);
                            //受益村数
                            if (row.getCell(14).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                row.getCell(14).setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setVillagePoverty(Long.valueOf(StringUtils.isNotEmpty(row.getCell(14).getStringCellValue()) ? row.getCell(14).getStringCellValue() : "0"));
                            if (row.getCell(15).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                row.getCell(15).setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setVillageOther(Long.valueOf(StringUtils.isNotEmpty(row.getCell(15).getStringCellValue()) ? row.getCell(15).getStringCellValue() : "0"));
                            //收益户数
                            if (row.getCell(16).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                row.getCell(16).setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setHouseSubtotal(Double.valueOf(StringUtils.isNotEmpty(row.getCell(16).getStringCellValue()) ? row.getCell(16).getStringCellValue() : "0.0000"));
                            if (row.getCell(17).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                row.getCell(17).setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setHousePoverty(Double.valueOf(StringUtils.isNotEmpty(row.getCell(17).getStringCellValue()) ? row.getCell(17).getStringCellValue() : "0.0000"));
                            if (row.getCell(18).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                row.getCell(18).setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setHouseOther(Double.valueOf(StringUtils.isNotEmpty(row.getCell(18).getStringCellValue()) ? row.getCell(18).getStringCellValue() : "0.0000"));
                            //受益人数
                            if (row.getCell(19).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                row.getCell(19).setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setPeopleSubtotal(Double.valueOf(StringUtils.isNotEmpty(row.getCell(19).getStringCellValue()) ? row.getCell(19).getStringCellValue() : "0.0000"));
                            if (row.getCell(20).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                row.getCell(20).setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setPeoplePoverty(Double.valueOf(StringUtils.isNotEmpty(row.getCell(20).getStringCellValue()) ? row.getCell(20).getStringCellValue() : "0.0000"));
                            if (row.getCell(21).getCellType() == CellType.NUMERIC) {
                                // 如果单元格是数字类型，则将其转换为字符串类型
                                row.getCell(21).setCellType(CellType.STRING);
                            }
                            infoProjectPlan.setPeopleOther(Double.valueOf(StringUtils.isNotEmpty(row.getCell(21).getStringCellValue()) ? row.getCell(21).getStringCellValue() : "0.0000"));

                            if (StringUtils.isNotEmpty(row.getCell(22).getStringCellValue())){
                                SysDept sysDept = iSysDeptService.selectDeptByName(row.getCell(22).getStringCellValue());
                                if (StringUtils.isNull(sysDept)){
                                    throw  new RuntimeException(row.getCell(22).getStringCellValue()+"该单位不存在，请先添加！");
                                }else {
                                    infoProjectPlan.setSponsorTitle(sysDept.getDeptName());
                                    infoProjectPlan.setSponsorId(sysDept.getDeptId());
                                }
                            }
                            infoProjectPlan.setSponsorPeople(StringUtils.isNotEmpty(row.getCell(23).getStringCellValue()) ? row.getCell(23).getStringCellValue() : null);
                            if (StringUtils.isNotEmpty(row.getCell(24).getStringCellValue())){
                                SysDept sysDept = iSysDeptService.selectDeptByName(row.getCell(24).getStringCellValue());
                                if (StringUtils.isNull(sysDept)){
                                    throw  new RuntimeException(row.getCell(24).getStringCellValue()+"该单位不存在，请先添加！");
                                }else {
                                    infoProjectPlan.setImplementTitle(sysDept.getDeptName());
                                    infoProjectPlan.setImplementId(sysDept.getDeptId());
                                }
                            }
                            infoProjectPlan.setImplementPeople(StringUtils.isNotEmpty(row.getCell(25).getStringCellValue()) ? row.getCell(25).getStringCellValue() : null);
                            infoProjectPlan.setApprovalNumber(row.getCell(26).getStringCellValue());
                            infoProjectPlan.setRemarks(row.getCell(27).getStringCellValue());
                            infoProjectPlan.setCreateBy(SecurityUtils.getUsername());
                            infoProjectPlan.setCreateTime(new Date());
                            infoProjectPlan.setUpdateTime(new Date());
                            infoProjectPlanService.insertInfoProjectPlan(infoProjectPlan);
                        }
                    }
                }
            }
            return AjaxResult.success("导入成功！");
        } catch (IOException e) {
            throw new RuntimeException("模板错误！");
        }
    }

    //判断是否是纯数字
    public static boolean isNumeric(String str) {
        if (str == null || str.length() == 0) {
            return false;
        }
        // 判断字符串是否全部由数字组成，如果是则返回true，否则返回false
        return str.matches("\\d+");
    }

    @PostMapping("/batchImplementProject")
    public AjaxResult batchImplementProject(@RequestBody JSONObject jsonObject){
        JSONArray ids = jsonObject.getJSONArray("ids");
        List<Long> collect1 = ids.stream().map(Object::toString).mapToLong(Long::parseLong).boxed().collect(Collectors.toList());
        for (Long aLong : collect1) {
            InfoProjectPlan infoProjectPlan = new InfoProjectPlan();
            infoProjectPlan.setId(aLong);
            implementProject(infoProjectPlan);
        }
        return AjaxResult.success();
    }

    /**
     * 下达接口
     * @param infoProjectPlan
     * @return
     */
    @PostMapping("/implementProject")
    public AjaxResult implementProject(@RequestBody InfoProjectPlan infoProjectPlan) {
        InfoProjectPlan infoProjectPlan1 = infoProjectPlanService.selectInfoProjectPlanById(infoProjectPlan.getId());
        InfoProjectTarget infoProjectTarget = new InfoProjectTarget();
        infoProjectTarget.setBaseProjectId(infoProjectPlan.getId());
        //金额
        infoProjectTarget.setTotalFunds(infoProjectPlan.getFundSum());
        infoProjectTarget.setCentralFund(infoProjectPlan.getCentreFund());
        infoProjectTarget.setProvincialFunds(infoProjectPlan.getProvincialLevelFund());
        infoProjectTarget.setMunicipalLevelFund(infoProjectPlan.getMunicipalLevelFund());
        infoProjectTarget.setCountyLevelFund(infoProjectPlan.getCountyLevelFund());
        //主管
        String implementTitle = infoProjectPlan1.getImplementTitle();
        String sponsorTitle = infoProjectPlan1.getSponsorTitle();
        SysDept implementDept = iSysDeptService.selectDeptByName(implementTitle);
        if (StringUtils.isNull(implementDept)){
            throw new RuntimeException("项目未先选择实施单位！");
        }
        SysDept sponsorDept = iSysDeptService.selectDeptByName(sponsorTitle);
        if (StringUtils.isNull(sponsorDept)){
            throw new RuntimeException("项目未先选择主管单位！");
        }
        infoProjectTarget.setDepartmentId(sponsorDept.getDeptId());
        infoProjectTarget.setReleaseDepartmentId(implementDept.getDeptId());
        int i = infoProjectTargetMapper.insertInfoProjectTarget(infoProjectTarget);
        if (i == 1) {
            infoProjectPlan.setStatus(1);
            int j = infoProjectPlanService.updateInfoProjectPlan(infoProjectPlan);
            return AjaxResult.success("实施成功！");
        }
       return AjaxResult.error();
    }
}
